//
//  QWNetworkRequest.m
//  Pods
//
//  Created by ZhangYanhua on 15/12/9.
//
//

#import "QWNetworkRequest.h"
#import "QWNetworkAgent.h"
#import "QWNetworkConfig.h"
#import "QWNetworkHelpers.h"

@implementation QWNetworkRequest

/// append self to request queue
- (void)start {
    [[QWNetworkAgent sharedInstance] addRequest:self];
}

/// remove self from request queue
- (void)stop {
    [[QWNetworkAgent sharedInstance] cancelRequest:self];
}

- (BOOL)isExecuting
{
    return (_sessionTask.state == NSURLSessionTaskStateRunning);
}

- (void)startWithCompletionBlockWithSuccess:(void (^)(QWNetworkRequest *request))success
                                    failure:(void (^)(QWNetworkRequest *request))failure {
    [self setCompletionBlockWithSuccess:success failure:failure];
    [self start];
}

- (void)setCompletionBlockWithSuccess:(void (^)(QWNetworkRequest *request))success
                              failure:(void (^)(QWNetworkRequest *request))failure {
    self.successCompletionBlock = success;
    self.failureCompletionBlock = failure;
}

- (void)clearCompletionBlock {
    // nil out to break the retain cycle.
    self.successCompletionBlock = nil;
    self.failureCompletionBlock = nil;
}

#pragma mark -
#pragma mark 缓存实现

- (id)cacheKeyFilterForRequestArgument:(id)argument
{
    return argument;
}

- (NSTimeInterval)cacheTimeOutSeconds
{
    return 0;
}

- (id)getCachedJson
{
// FIXZHY: 替换通用的缓存方式，需要加入过期时间，创建时间, 考虑token有关的时候如何处理
    return [[NSUserDefaults standardUserDefaults] objectForKey:[self cacheKey]];
}

- (NSString *)cacheKey
{
    NSString *requestUrl = [self requestUrl];
    NSString *baseUrl = [QWNetworkConfig sharedInstance].baseUrl;
    id argument = [self cacheKeyFilterForRequestArgument:[self requestArgument]];
    NSString *requestInfo = [NSString stringWithFormat:@"Method:%ld Host:%@ Url:%@ Argument:%@",
                             (long)[self requestMethod],
                             baseUrl,
                             requestUrl,
                             argument];

    NSString *cacheKey = [QWNetworkHelpers md5StringFromString:requestInfo];
    return cacheKey;
}

- (void)saveJsonResponseToCacheFile:(id)jsonResponse
{
    if ([self cacheTimeOutSeconds] > 0) {
// FIXZHY: 替换通用的缓存方式，需要加入过期时间，创建时间
        [[NSUserDefaults standardUserDefaults] setObject:jsonResponse
                                                  forKey:[self cacheKey]];
    }
}

#pragma mark -
#pragma mark QWNetworkDataSource

- (NSString *)requestUrl
{
    return @"";
}

- (NSString *)cdnUrl
{
    return @"";
}

- (NSString *)baseUrl
{
    return @"";
}

- (BOOL)useCDN
{
    return NO;
}


- (NSTimeInterval)requestTimeoutInterval
{
    return 30;
}

- (NSMutableDictionary *)requestArgument
{
    return [NSMutableDictionary dictionary];
}

- (QWRequestMethod)requestMethod
{
    return QWRequestMethodPost;
}

- (QWRequestSerializerType)requestSerializerType
{
    return QWRequestSerializerTypeHTTP;
}

- (NSArray *)requestAuthorizationHeaderFieldArray
{
    return nil;
}

- (NSDictionary *)requestHeaderFieldValueDictionary
{
    return nil;
}


- (AFConstructingBlock)constructingBodyBlock
{
    return nil;
}

- (NSString *)resumableDownloadPath
{
    return nil;
}

#pragma mark -
#pragma mark QWNetworkDelegate

- (BOOL)handleResultWithResonseData:(id)responseData error:(NSError *)error
{
    NSAssert(NO, @"业务层必须实现此方法，根据和服务器的通信规范返回正确结果");
    
    return NO;
}

- (AFDownloadProgressBlock)resumableDownloadProgressBlock
{
    return nil;
}

- (void)requestCompleteFilterWithResponseData:(id)responseData
{
    [self saveJsonResponseToCacheFile:responseData];
}

- (void)requestFailedFilterWithError:(NSError *)error
{
}

@end
